﻿using Acb.Core.Data;
using Acb.Core.Extensions;
using Acb.Core.Helper;
using Acb.Dapper;
using Acb.Dapper.Domain;
using Dapper;
using OAuth.Server.Domain.Entities;
using OAuth.Server.Domain.Enums;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OAuth.Server.Domain
{
    public class ResourceRepository : DapperRepository<TResource>
    {
        public async Task<IEnumerable<TResource>> QueryByNames(IEnumerable<string> names, ResourceType type)
        {
            var modelType = typeof(TResource);
            var sql =
                $"SELECT {modelType.Columns()} FROM [{modelType.PropName()}] WHERE [{nameof(TResource.Name)}]=ANY(@names) AND [{nameof(TResource.Type)}]=@type";
            sql = Connection.FormatSql(sql);
            return await Connection.QueryAsync<TResource>(sql, new { names = names.ToArray(), type });
        }

        public async Task<TResource> QueryByName(string name, ResourceType type)
        {
            var modelType = typeof(TResource);
            var sql =
                $"SELECT {modelType.Columns()} FROM [{modelType.PropName()}] WHERE [{nameof(TResource.Name)}]=@name AND [{nameof(TResource.Type)}]=@type";
            sql = Connection.FormatSql(sql);
            return await Connection.QueryFirstAsync<TResource>(sql, new { name, type });
        }

        public async Task<IEnumerable<TResource>> QueryAll()
        {
            return await Connection.QueryAllAsync<TResource>();
        }

        public async Task<int> InsertSecrets(TSecret secret)
        {
            secret.Id = IdentityHelper.NewSequentialGuid();
            secret.Source = (byte)SecretSource.Resource;
            return await Connection.InsertAsync(secret);
        }
    }
}
